package cn.sakura.security.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import cn.sakura.api.moudle.admin.SysUserService;
import cn.sakura.common.domain.LoginUserInfo;
import cn.sakura.common.domain.admin.entity.SysUser;
import cn.sakura.common.utils.JwtUtil;
import cn.sakura.common.utils.LocalUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    SysUserService userService;

    /**
     * 请求执行前执行的，将用户信息放入ThreadLocal
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LoginUserInfo user;
        String userId = jwtUtil.getUserIdByRequest(request);
        if (StringUtils.isBlank(userId)) {
            log.info("***************************用户未登录， ThreadLocal无信息***************************");
            return true;
        }
        SysUser sysUser = userService.getById(userId);
        user = BeanUtil.copyProperties(sysUser, LoginUserInfo.class);
        if (null != user) {
            log.info("***************************用户已登录，用户信息放入ThreadLocal***************************");
            LocalUserUtil.addCurrentUser(user);
            log.info("***************************用户信息：***************************");
            log.info(JSONUtil.toJsonStr(user));
            return true;
        }
        log.info("***************************用户未登录， ThreadLocal无信息***************************");
        return true;
    }

    /**
     * 接口访问结束后，从ThreadLocal中删除用户信息
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("***************************接口调用结束， 从ThreadLocal删除用户信息***************************");
        LocalUserUtil.remove();
    }
}
